import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:mahjong/entity/Restful.dart';
import 'package:mahjong/util/DictionaryConst.dart';
import 'package:mahjong/util/Http.dart';
import 'package:mahjong/util/PageInfo.dart';

typedef _BuildItem = Widget Function(dynamic data);

typedef _LoadingData = Widget Function(PageInfo data);

const String _dataItemNodeConst = "records";
const String _pageSizeNodeConst = "size";
const String _pageCurrentNodeConst = "current";
const String _pageTotalNodeConst = "total";
const String _pagesNodeConst = "pages";

class PagingEasyRefresh extends StatefulWidget {
  final _BuildItem buildItem;
  final PageInfo pageInfo;
  final String dataItemNode;
  final String pageSizeNode;
  final String pageCurrentNode;
  final String pageTotalNode;
  final String pagesNode;
  final Map<String, dynamic> parame;
  PagingEasyRefresh(
      {Key key,
      this.buildItem,
      this.pageInfo,
      this.dataItemNode: _dataItemNodeConst,
      this.pageSizeNode: _pageSizeNodeConst,
      this.pageCurrentNode: _pageCurrentNodeConst,
      this.pageTotalNode: _pageTotalNodeConst,
      this.pagesNode: _pagesNodeConst,
      this.parame})
      : super(key: key);

  @override
  _PagingEasyRefreshState createState() => _PagingEasyRefreshState();
}

class _PagingEasyRefreshState extends State<PagingEasyRefresh> {
  EasyRefreshController _controller;
  PageInfo _pageInfo;
  String _dataItemNode;
  String _pageSizeNode;
  String _pageCurrentNode;
  String _pageTotalNode;
  String _pagesNode;
  List<dynamic> pageData;
  _BuildItem _buildItem;
  Map<String, dynamic> _parame;

  bool fistLoading = true;

  @override
  void initState() {
    super.initState();
    _parame = widget.parame ?? {};
    _buildItem = widget.buildItem;
    _dataItemNode = widget.dataItemNode;
    _pageSizeNode = widget.pageSizeNode;
    _pageCurrentNode = widget.pageCurrentNode;
    _pageTotalNode = widget.pageTotalNode;
    _pagesNode = widget.pagesNode;
    pageData = [];
    _pageInfo = widget.pageInfo == null ? PageInfo.init(1, 5) : widget.pageInfo;
    initData();
    _controller = EasyRefreshController();
  }

  void initData({_LoadingData success, bool reflush: false}) {
    initParamePageInfo();
    Http.getInstance().request<Restful>(DictionaryConst.historyRecode,
        data: _parame, success: (data) {
      if (reflush) {
        pageData = [];
        _controller.resetLoadState();
      }
      if (fistLoading) {
        fistLoading = false;
      }
      Map<dynamic, dynamic> resultData;
      if (!(data.body is Map)) {
        setState(() {});
        return;
      }
      resultData = Map.castFrom(data.body);
      if (!(resultData[_dataItemNode] is List)) {
        return;
      }
      List<dynamic> items = List.castFrom(resultData[_dataItemNode]);
      items.forEach((element) {
        pageData.add(_buildItem(element));
      });
      if (null != success) {
        success(PageInfo.factory(
            current: resultData[_pageCurrentNode],
            pages: resultData[_pagesNode]));
      }
      _controller.finishLoad(
          noMore: resultData[_pagesNode] == resultData[_pageCurrentNode]);

      setState(() {});
    }, error: (data) {
      if (fistLoading) {
        fistLoading = false;
      }
    });
  }

  void initParamePageInfo() {
    _parame[_pageCurrentNode] = _pageInfo.current;
    _parame[_pageSizeNode] = _pageInfo.size;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        pageData.length == 0
            ? AnimatedContainer(
                duration: Duration(microseconds: 200),
                child: Center(
                    child: fistLoading
                        ? CircularProgressIndicator()
                        : Text(
                            "暂时没有相关数据",
                          )),
              )
            : SizedBox(),
        EasyRefresh.custom(
          enableControlFinishRefresh: false,
          enableControlFinishLoad: true,
          controller: _controller,
          header: ClassicalHeader(
              refreshText: "下拉刷新",
              refreshingText: "刷新数据中...",
              refreshReadyText: "释放手刷新",
              refreshedText: "刷新完成"),
          footer: ClassicalFooter(
              loadText: "加载更多",
              loadingText: "正在加载...",
              loadedText: "加载完成",
              noMoreText: "没有更多数据了..."),
          onRefresh: () async {
            _pageInfo.current = 1;
            initData(reflush: true);
          },
          onLoad: () async {
            _pageInfo.current++;
            initData();
          },
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return pageData[index];
                },
                childCount: pageData.length,
              ),
            ),
          ],
        )
      ],
    );
  }
}
